﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using FileManagerGlobal_Library;
using FileManager_Server.BusinessLogic.IRepository_Service;
using FileManager_Server.BusinessLogic.WCF.ObjectContainer_Setting;
using FileManager_Server.ServiceModel.DataTransfer_Model;
using FileManager_Server.ServiceModel.WCF_Args_Model;
using FileManager_Server.Utility;
using Newtonsoft.Json;

namespace FileManager_Server.BusinessLogic.WCF
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "FileTransfer_Service" in both code and config file together.
    public class FileTransfer_Service : IFileTransfer_Service
    {
        //public void UploadFile(RemoteFileInfo request)
        //{
        //    var fileAttchInfo = JsonConvert.DeserializeObject<FileAttchInfo>(request.JsonData);
        //    var fileService = ObjectContainerInstance.Instance.UnityObject_Container.GetInterfaceService<IFileService>();
        //    fileService.UploadFile(request, fileAttchInfo);
        //}

        //public RemoteFileInfo DownloadFile(DownloadRequest request)
        //{
        //    var fileService = ObjectContainerInstance.Instance.UnityObject_Container.GetInterfaceService<IFileService>();
        //    return fileService.DownloadFile(request);
        //}

        private static object LockFile = new object();
        public void UplodaFileOneWay(UploadFileInfo file)
        {
            try
            {
                var filePath = file.Name + GlobalVariable.FileTempExtension;
                if(File.Exists(filePath))
                {
                    lock (LockFile)
                    {
                        //var fs = File.OpenWrite(filePath);
                        var fs = new FileStream(filePath, FileMode.Open,FileAccess.Write,FileShare.Write);//打开文件
                        var offset = file.Offset;  //file.Offset 文件偏移位置,表示从这个位置开始进行后面的数据添加
                        var writer = new BinaryWriter(fs);//初始化文件写入器
                        // writer.Seek((int)offset, SeekOrigin.Begin);//设置文件的写入位置
                        // writer.Write(file.Data, (int)offset,file.Data.Length);//写入数据
                        fs.Position = offset;
                        //writer.Seek((int) offset, SeekOrigin.Begin);
                        writer.Write(file.Data);
                        file.Offset += file.Data.Length;//返回追加数据后的文件位置
                        file.Data = null;
                        writer.Close();
                        fs.Close();
                    }
                }
            }
            catch (Exception)
            {
                
                throw;
            }
        }


        public void ReNameFile(UploadingSuccessArgs uploadingSuccessArgs)
        {
            try
            {
                var filePath = uploadingSuccessArgs.RenameFilePath + GlobalVariable.FileTempExtension;
                if (File.Exists(filePath))
                {
                    lock (LockFile)
                    {
                        if (File.Exists(uploadingSuccessArgs.RenameFilePath))
                            File.Delete(uploadingSuccessArgs.RenameFilePath);
                        File.Move(filePath,
                                  filePath.Replace(GlobalVariable.FileTempExtension, ""));
                    }
                    var fileService =
                        ObjectContainerInstance.Instance.UnityObject_Container.GetInterfaceService<IFileService>();
                    fileService.UploadingFileSuccess(uploadingSuccessArgs);
                }

            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("ReNameFile has problem", ex);
            }
        }


        public void UplodaFile(UploadFileInfo file)
        {
            try
            {
                var filePath = file.Name + GlobalVariable.FileTempExtension;
                if (File.Exists(filePath))
                {
                    lock (LockFile)
                    {
                        //var fs = File.OpenWrite(filePath);
                        var fs = new FileStream(filePath, FileMode.Open, FileAccess.Write, FileShare.Write);//打开文件
                        var offset = file.Offset;  //file.Offset 文件偏移位置,表示从这个位置开始进行后面的数据添加
                        var writer = new BinaryWriter(fs);//初始化文件写入器
                        // writer.Seek((int)offset, SeekOrigin.Begin);//设置文件的写入位置
                        // writer.Write(file.Data, (int)offset,file.Data.Length);//写入数据
                        fs.Position = offset;
                        //writer.Seek((int) offset, SeekOrigin.Begin);
                        writer.Write(file.Data);
                        file.Offset += file.Data.Length;//返回追加数据后的文件位置
                        file.Data = null;
                        writer.Close();
                        fs.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("UplodaFile has problem", ex); 
            }
        }


        public DownloadingResult DownloadingFile(FileDownloadingArgs fileDownloadingArgs)
        {
            try
            {
                var result = new DownloadingResult {DataTransfer = new byte[fileDownloadingArgs.DataLength]};
                using(var fileStream = new FileStream(fileDownloadingArgs.ServerPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    fileStream.Position = fileDownloadingArgs.Offset;
                    fileStream.Read(result.DataTransfer, 0, result.DataTransfer.Length);
                }
                return result;
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("DownloadingFile has problem", ex);
                throw;
            }
        }
    }
}
